#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>


static dev_t dev_num;

struct cdev cdev_test;
struct file_operations cdev_test_ops = {
    .owner = THIS_MODULE        //将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块
};


static int __init module_cdev_init(void)
{
    int ret ;
    int major, minor;

    ret = alloc_chrdev_region(&dev_num, 0, 1, "chrdev_test");
    if (ret < 0)
    {
        printk(KERN_EMERG "alloc register chrdev error\r\n");
    }
    printk(KERN_EMERG "alloc register chrdev ok\r\n");

    major = MAJOR(dev_num);
    minor = MINOR(dev_num);
    printk(KERN_EMERG "major is %d \r\n", major);
    printk(KERN_EMERG "minor is %d \r\n", minor);

    cdev_init(&cdev_test, &cdev_test_ops);
    cdev_test.owner = THIS_MODULE;      //将owner字段指向本模块，可以避免在模块的操作正在被使用时卸载该模块

    ret = cdev_add(&cdev_test, dev_num, 1);
    if (ret < 0)
    {
        printk(KERN_EMERG "cdev add is error\r\n");
    }
    printk(KERN_EMERG "cdev_add is ok\r\n");
    return 0;
}

static void __exit module_cdev_exit(void)
{

    cdev_del(&cdev_test);
    unregister_chrdev_region(dev_num, 1);
    printk(KERN_EMERG "module exit\r\n");
}

module_init(module_cdev_init);
module_exit(module_cdev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("treasure1029");


